<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class WithdrawAuto extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\WithdrawAuto;
    }

    public function transfer(){
        $ids = $this->request->param('ids');
        $ids = explode(',', $ids);
        $ids = array_filter($ids);
        if (!$ids) $this->error('传入值出错!');
        $data = [];
        foreach ($ids as $k => $v) {
            $res = $this->CommonWithdrawModel->where(['id'=>$v])->find();
            if ($res && $res['transfer_status'] !== 1) {
                if ($res['withdraw_type'] == '微信' || $res['withdraw_type'] == '支付宝' || $res['withdraw_type'] == 'QQ钱包') {
                    $data[] = $res;
                }
            }
        }
        if (!$data) $this->error('没有可操作的数据!');
        $list = [];
        foreach ($data as $k => $v) {
            if ($v['withdraw_type'] == '微信') {
                $transfer = WxTransfer($v['withdraw_account'],$v['withdraw_name'],$v['realmoney']);
            }elseif ($v['withdraw_type'] == '支付宝') {
                $transfer = AliTransfer($v['withdraw_account'],$v['withdraw_name'],$v['realmoney']);
            }else{
                if (!is_numeric($v['withdraw_account']) || strlen($v['withdraw_account'])<6 || strlen($v['withdraw_account'])>10) {
                    $list[] = [
                        'id'=>$v['id'],
                        'status'=>2,
                        'msg'=>'QQ号码格式错误',
                    ];
                    continue;
                }
                $transfer = QQTransfer($v['withdraw_account'],$v['realmoney'],config('site.qqpay_transfer_memo'));
            }
            if (isset($transfer['code']) && $transfer['code']) {
                $this->CommonWithdrawModel->where(['id'=>$v['id']])->update(['transfer_status'=>1,'transfer_result'=>$transfer['payment_no'],'transfer_date'=>$transfer['payment_time']]);
                
                if ($v['status'] == 2) {
                    $user = $this->CommonUserModel->where(['id'=>$v['uid']])->find();
                    if ($user) {
                        $newmoney = round($user['money']-$v['money'],2);
                        $this->CommonUserModel->where(['id'=>$v['uid']])->update(['money'=>$newmoney]);
                    }
                }

                $this->CommonWithdrawModel->where(['id'=>$v['id']])->update(['status'=>1,'back'=>'']);

                $list[] = [
                    'id'=>$v['id'],
                    'status'=>1,
                    'msg'=>'成功',
                ];
            }else{
                $list[] = [
                    'id'=>$v['id'],
                    'status'=>2,
                    'msg'=>isset($transfer['msg'])?$transfer['msg']:'失败',
                ];
            }
        }
        return json(['code'=>1,'msg'=>'OK','data'=>$list]);
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            try {
                $this->model->where(['id'=>$row['id']])->update(['status'=>1]);

                $list = $this->CommonWithdrawModel->where(['mark'=>$row['mark'],'status'=>0])->select();

                $this->CommonWithdrawModel->where(['mark'=>$row['mark'],'status'=>0])->update(['status'=>1]);
				$this->success();
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $where = [];
        !empty(input('get.type')) ? $where['withdraw_type'] = input('get.type') : [];
        $count = $this->CommonWithdrawModel->where(['mark'=>$row['mark']])->where($where)->order('id desc')->count();
        $money = $this->CommonWithdrawModel->where(['mark'=>$row['mark']])->where($where)->sum('realmoney');
        $list = $this->CommonWithdrawModel->where(['mark'=>$row['mark']])->where($where)->order('id desc')->select();
        foreach ($list as $k => &$v) {
            $v['api_id'] = $this->CommonUserModel->where(['id'=>$v['uid']])->find()['api_id'];
        }
        $this->view->assign("count", $count);
        $this->view->assign("money", $money);
        $this->view->assign("list", $list);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 手动
     */
    public function editt($ids = NULL)
    {
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            try {
                $this->CommonWithdrawModel->where(['type'=>1,'status'=>0])->whereTime('createtime','today')->update(['status'=>1]);
                $this->success();
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $where = [];
        $where['type'] = 1;
        !empty(input('get.type')) ? $where['withdraw_type'] = input('get.type') : [];
        $count = $this->CommonWithdrawModel->where($where)->whereTime('createtime','today')->order('id desc')->count();
        $money = $this->CommonWithdrawModel->where($where)->whereTime('createtime','today')->sum('realmoney');
        $list = $this->CommonWithdrawModel->where($where)->whereTime('createtime','today')->order('id desc')->select();
        foreach ($list as $k => &$v) {
            $v['api_id'] = $this->CommonUserModel->where(['id'=>$v['uid']])->find()['api_id'];
        }
        $action = $this->request->action();
        $this->view->assign("action", $action);
        $this->view->assign("count", $count);
        $this->view->assign("money", $money);
        $this->view->assign("list", $list);
        return $this->view->fetch('edit');
    }

    /**
     * 手动
     */
    public function edittt($ids = NULL)
    {
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            try {
                $this->CommonWithdrawModel->where(['type'=>1,'status'=>0])->whereTime('createtime','yesterday')->update(['status'=>1]);
                $this->success();
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $where = [];
        $where['type'] = 1;
        !empty(input('get.type')) ? $where['withdraw_type'] = input('get.type') : [];
        $count = $this->CommonWithdrawModel->where($where)->whereTime('createtime','yesterday')->order('id desc')->count();
        $money = $this->CommonWithdrawModel->where($where)->whereTime('createtime','yesterday')->sum('realmoney');
        $list = $this->CommonWithdrawModel->where($where)->whereTime('createtime','yesterday')->order('id desc')->select();
        foreach ($list as $k => &$v) {
            $v['api_id'] = $this->CommonUserModel->where(['id'=>$v['uid']])->find()['api_id'];
        }
        $action = $this->request->action();
        $this->view->assign("count", $count);
        $this->view->assign("action", $action);
        $this->view->assign("money", $money);
        $this->view->assign("list", $list);
        return $this->view->fetch('edit');
    }

    public function export($ids = NULL){
        $row = $this->model->get($ids);
        if (!$row) $this->error(__('No Results were found'));
        $list = $this->CommonWithdrawModel->where(['mark'=>$row['mark']])->order('id desc')->select();
        $data = [];
        foreach ($list as $k => $v) {
            if ($v['status'] == 0) {
                $v['status'] = '待处理';
            }elseif ($v['status'] == 1) {
                $v['status'] = '已完成';
            }else{
                $v['status'] = '失败';
            }
            $r = [
                'id'=>$v['id'],
                'status'=>$v['status'],
                'withdraw_type'=>$v['withdraw_type'],
                'withdraw_name'=>$v['withdraw_name'],
                'withdraw_account'=>$v['withdraw_account'],
                'money'=>$v['money'],
                'realmoney'=>$v['realmoney'],
                'percent'=>$v['percent'],
                'createtime'=>date('Y-m-d H:i:s',$v['createtime']),
            ];
            $data[] = $r;
        }
        $array = [];
        foreach ($data as $k => $v) {
            if ($v['withdraw_type'] == '微信') {
                $array[] = $v;
            }
        }
        $array[] = [
            'id'=>'',
            'status'=>'',
            'withdraw_type'=>'',
            'withdraw_name'=>'',
            'withdraw_account'=>'',
            'money'=>'',
            'realmoney'=>'',
            'percent'=>'',
            'createtime'=>'',
        ];
        foreach ($data as $k => $v) {
            if ($v['withdraw_type'] == '支付宝') {
                $array[] = $v;
            }
        }
        $array[] = [
            'id'=>'',
            'status'=>'',
            'withdraw_type'=>'',
            'withdraw_name'=>'',
            'withdraw_account'=>'',
            'money'=>'',
            'realmoney'=>'',
            'percent'=>'',
            'createtime'=>'',
        ];
        foreach ($data as $k => $v) {
            if ($v['withdraw_type'] == 'QQ钱包') {
                $array[] = $v;
            }
        }
        $data = $array;
        $phpexcelSrc=APP_PATH.'phpexcel/PHPExcel.php';
        include "$phpexcelSrc";
        $phpexcel=new \PHPExcel();
        $phpexcel->setActiveSheetIndex(0);
        $sheet=$phpexcel->getActiveSheet();
        $arr=[
            'id'=>'id',
            'status'=>'状态',
            'withdraw_type'=>'提现方式',
            'withdraw_name'=>'真实姓名',
            'withdraw_account'=>'提现账号',
            'money'=>'提现金额',
            'realmoney'=>'实际到账',
            'percent'=>'手续费',
            'createtime'=>'创建时间',
        ];
        array_unshift($data, $arr);
        $currow=0;
        foreach ($data as $k => $v) {
            $currow=$k+1;
            $sheet->setCellValue('A'.$currow,$v['id'])
                  ->setCellValue('B'.$currow,$v['status'])
                  ->setCellValue('C'.$currow,$v['withdraw_type'])
                  ->setCellValue('D'.$currow,$v['withdraw_name'])
                  ->setCellValue('E'.$currow,$v['withdraw_account'])
                  ->setCellValue('F'.$currow,$v['money'])
                  ->setCellValue('G'.$currow,$v['realmoney'])
                  ->setCellValue('H'.$currow,$v['percent'])
                  ->setCellValue('I'.$currow,$v['createtime'])
            ;
        }
        header('Content-Type: application/vnd.ms-excel');//设置下载前的头信息
        header('Content-Disposition: attachment;filename="export.xlsx"');
        header('Cache-Control: max-age=0');
        $phpwriter=new \PHPExcel_Writer_Excel2007($phpexcel);
        $phpwriter->save('php://output');
        return;
    }
}
